package pl.matt.media.utils;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.PixelGrabber;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.media.jai.Histogram;
import javax.media.jai.JAI;
import javax.media.jai.LookupTableJAI;
import javax.media.jai.PlanarImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.SeekableStream;

public class ImageUtils {

	private static final String DEFAULT_IMAGE_FORMAT = "jpeg";
	
	/**
	 * zapisuje opraz do pliku jpeg
	 * 
	 * @param photo
	 * @param filename
	 * @throws IOException
	 * @throws ImageFormatException
	 */
	public static final void encodeAndSaveImageJPEG(Image photo, String filename) throws ImageFormatException,
			IOException {
		BufferedImage bi = new BufferedImage(photo.getWidth(null), photo.getHeight(null), BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = bi.createGraphics();
		g2.drawImage(photo, null, null);
		FileOutputStream out = null;

		out = new FileOutputStream(filename);
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
		param.setQuality(1.0f, false); // 100% high quality setting, no
		// compression
		encoder.setJPEGEncodeParam(param);
		encoder.encode(bi);
		out.close();
	}

	/**
	 * http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html This method
	 * returns a buffered image with the contents of an image
	 * 
	 * @param image
	 * @return
	 */
	public static BufferedImage toBufferedImage(Image image) {
		if (image == null) {
			return null;
		}
		if (image instanceof BufferedImage) {
			return (BufferedImage) image;
		}

		// This code ensures that all the pixels in the image are loaded
		image = new ImageIcon(image).getImage();

		// Determine if the image has transparent pixels; for this method's
		// implementation, see e661 Determining If an Image Has Transparent
		// Pixels
		boolean hasAlpha = hasAlpha(image);

		// Create a buffered image with a format that's compatible with the
		// screen
		BufferedImage bimage = null;
		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
		try {
			// Determine the type of transparency of the new buffered image
			int transparency = Transparency.OPAQUE;
			if (hasAlpha) {
				transparency = Transparency.BITMASK;
			}

			// Create the buffered image
			GraphicsDevice gs = ge.getDefaultScreenDevice();
			GraphicsConfiguration gc = gs.getDefaultConfiguration();
			bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
		} catch (HeadlessException e) {
			// The system does not have a screen
		}

		if (bimage == null) {
			// Create a buffered image using the default color model
			int type = BufferedImage.TYPE_INT_RGB;
			if (hasAlpha) {
				type = BufferedImage.TYPE_INT_ARGB;
			}
			bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
		}

		// Copy image to buffered image
		Graphics g = bimage.createGraphics();

		// Paint the image onto the buffered image
		g.drawImage(image, 0, 0, null);
		g.dispose();

		return bimage;
	}

	// 
	/**
	 * http://www.exampledepot.com/egs/java.awt.image/HasAlpha.html This method
	 * returns true if the specified image has transparent pixels
	 * 
	 * @param image
	 * @return
	 */
	public static boolean hasAlpha(Image image) {
		// If buffered image, the color model is readily available
		if (image instanceof BufferedImage) {
			BufferedImage bimage = (BufferedImage) image;
			return bimage.getColorModel().hasAlpha();
		}

		// Use a pixel grabber to retrieve the image's color model;
		// grabbing a single pixel is usually sufficient
		PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
		try {
			pg.grabPixels();
		} catch (InterruptedException e) {
		}

		// Get the image's color model
		ColorModel cm = pg.getColorModel();
		return cm.hasAlpha();
	}

	/**
	 * przycina obraz
	 * 
	 * @param source
	 *            obraz żródłowy
	 * @param x
	 *            współrzędna x początku obrazu do wycięcia
	 * @param y
	 *            współrzędna y początku obrazu do wycięcia
	 * @param width
	 *            szerokość przycięcia
	 * @param height
	 *            wysokość przycięcia
	 * @return przycięty obraz
	 */
	public static final Image cropImage(Image source, int x, int y, int width, int height) {
		// This code ensures that all the pixels in the image are loaded
		Image image = new ImageIcon(source).getImage();

		// Determine if the image has transparent pixels; for this method's
		// implementation, see e661 Determining If an Image Has Transparent
		// Pixels
		boolean hasAlpha = hasAlpha(image);

		// Create a buffered image with a format that's compatible with the
		// screen
		BufferedImage bimage = null;
		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
		try {
			// Determine the type of transparency of the new buffered image
			int transparency = Transparency.OPAQUE;
			if (hasAlpha) {
				transparency = Transparency.BITMASK;
			}

			// Create the buffered image
			GraphicsDevice gs = ge.getDefaultScreenDevice();
			GraphicsConfiguration gc = gs.getDefaultConfiguration();
			bimage = gc.createCompatibleImage(width, height, transparency);
		} catch (HeadlessException e) {
			// The system does not have a screen
			e.printStackTrace();
		}

		if (bimage == null) {
			// Create a buffered image using the default color model
			int type = BufferedImage.TYPE_INT_RGB;
			if (hasAlpha) {
				type = BufferedImage.TYPE_INT_ARGB;
			}
			bimage = new BufferedImage(width, height, type);
		}

		// Copy image to buffered image
		Graphics g = bimage.createGraphics();

		// Paint the image onto the buffered image
		g.drawImage(image, 0, 0, 0 + width, 0 + height, x, y, x + width, y + height, null);
		g.dispose();
		return bimage;
	}

	public static void showImage(Image image) {
		ImageIcon icon = new ImageIcon(image);
		JPanel panel = new JPanel();
		panel.add(new JLabel(icon));
		JFrame frame = new JFrame();
		frame.getContentPane().add(panel);
		frame.setSize(image.getWidth(null), image.getHeight(null));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	/**
	 * zapisuje obraz jako jpeg
	 * 
	 * @param image
	 * @param filename
	 * @param formatName
	 * @throws IOException
	 */
	public static final void writeImage(Image image, String filename, String formatName) throws IOException {
		BufferedImage bufferedImage = toBufferedImage(image);
		ImageIO.write(bufferedImage, formatName, new File(filename));
	}

	/**
	 * zapisuje obraz w jpegu
	 * 
	 * @param image
	 * @param filename
	 * @throws IOException
	 */
	public static final void writeImage(Image image, String filename) throws IOException {
		writeImage(image, filename, DEFAULT_IMAGE_FORMAT);
	}

	public static PlanarImage readImage(String filename) {
		PlanarImage image = null;

		// Use the JAI API unless JAI_IMAGE_READER_USE_CODECS is set
		if (System.getProperty("JAI_IMAGE_READER_USE_CODECS") == null) {
			image = JAI.create("fileload", filename);
		} else {
			try {
				// Use the ImageCodec APIs
				SeekableStream stream = new FileSeekableStream(filename);
				String[] names = ImageCodec.getDecoderNames(stream);
				ImageDecoder dec = ImageCodec.createImageDecoder(names[0], stream, null);
				RenderedImage im = dec.decodeAsRenderedImage();
				image = PlanarImage.wrapRenderedImage(im);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}

		// If the source image is colormapped, convert it to 3-band RGB.
		if (image.getColorModel() instanceof IndexColorModel) {
			// Retrieve the IndexColorModel
			IndexColorModel icm = (IndexColorModel) image.getColorModel();

			// Cache the number of elements in each band of the colormap.
			int mapSize = icm.getMapSize();

			// Allocate an array for the lookup table data.
			byte[][] lutData = new byte[3][mapSize];

			// Load the lookup table data from the IndexColorModel.
			icm.getReds(lutData[0]);
			icm.getGreens(lutData[1]);
			icm.getBlues(lutData[2]);

			// Create the lookup table object.
			LookupTableJAI lut = new LookupTableJAI(lutData);

			// Replace the original image with the 3-band RGB image.
			image = JAI.create("lookup", image, lut);
		}

		return image;
	}

	public static void main(String[] args) {
		/*
		 * RenderedImage im0 = JAI.create("fileload", "/tmp/1.pgm");
		 * System.out.println(im0);
		 */

		PlanarImage image = readImage("/home/mateusz/Desktop/tmp/eyes/BioID_1319jpeg");
		ParameterBlock pb1 = new ParameterBlock();
		pb1.addSource(image);
		PlanarImage dummyImage1 = JAI.create("histogram", pb1);
		Histogram histogram = (Histogram) dummyImage1.getProperty("histogram");
		System.out.println(histogram.getMean()[0]);
		// showImage(image.getAsBufferedImage());
		/*
		 * String readFormats[] = ImageIO.getReaderMIMETypes(); String
		 * writeFormats[] = ImageIO.getWriterMIMETypes();
		 * System.out.println("Readers: " + Arrays.asList(readFormats));
		 * System.out.println("Writers: " + Arrays.asList(writeFormats));
		 */

	}

}
